<template>
	<view class="box">
		<!-- 抢票日期 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">抢票日期</text>
			</view>
			<view class="box__time">
				<view class="box__time__box">
					<view
						class="box__time__box__item"
						v-for="(item, index) in timeList"
						:key="index"
						@click="item.stopEntering ? null : getTimeItem(item, index)"
						:class="{ change: index == timeIndex, isno: item.stopEntering }"
					>
						<text class="box__time__box__item__txt">{{ item.week !== undefined ? item.week : '延后时间段' }}</text>
						<text class="box__time__box__item__txt">{{ item.day }}</text>
						<text class="box__time__box__item__txt">{{ item.stopEntering ? '不可预约' : '可预约' }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 抢票时段 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">抢票时段</text>
			</view>
			<view class="box__timePrame">
				<view class="box__timePrame__box" :style="[listRowStyle]">
					<view
						class="box__timePrame__box__item"
						v-for="(item, index) in timePrameList"
						:key="index"
						@click="getTimeFrameItem(item, index)"
						:class="{ change: index == timeFrameIndex }"
					>
						<text>{{ item.startTime + '-' + item.endTime }}</text>
						<text style="margin-top: 15rpx">{{ item.surplusStock <= 0 ? '暂无余票' : '剩余票数：' + item.surplusStock }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 导游姓名 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">导游姓名</text>
			</view>
			<uv-input placeholder="请输入导游姓名" border="surround" clearable v-model="name"></uv-input>
		</view>
		<!-- 身份证号码 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">身份证号码</text>
			</view>
			<uv-input placeholder="请输入身份证号码" border="surround" clearable v-model="identificationCard"></uv-input>
		</view>
		<!-- 联系电话 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">联系电话</text>
			</view>
			<uv-input placeholder="请输入联系电话" border="surround" clearable v-model="phone"></uv-input>
		</view>

		<!-- 上传参观名单 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">参观名单</text>
				<text @click="getUserList(1)" class="box__item__list">查看参观名单</text>
			</view>
			<el-upload
				ref="visitingList"
				class="upload-demo"
				action="https://ticket.sxd.cn/api-api/app/clientHelper/uploadUserInfo"
				:headers="headers"
				:on-success="uploadSuccess"
				:on-exceed="uploadExceed"
				:data="{ teamType: 1 }"
				accept=".xlsx"
				:limit="1"
			>
				<el-button size="small" type="primary" @click="getUploadIndex(1)">点击上传</el-button>
			</el-upload>
		</view>

		<!-- 查看参观名单 -->
		<el-dialog title="提示" :visible.sync="dialogVisible" v-if="dialogVisible" width="90%">
			<el-table :data="tableData" style="width: 100%" v-if="dialogState == 1">
				<el-table-column prop="customerName" label="姓名" width="180"></el-table-column>
				<el-table-column prop="customerIdCard" label="身份证号" width="180"></el-table-column>
				<el-table-column prop="customerIdCardTypeStr" label="证件类型"></el-table-column>
				<el-table-column prop="customerPhone" label="手机号"></el-table-column>
				<el-table-column prop="productName" label="产品名称"></el-table-column>
			</el-table>
			<iframe :src="itineraryUrl" width="100%" height="500px" v-else></iframe>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 上传行程单 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">行程单</text>
				<text @click="getUserList(2)" class="box__item__list">查看行程单</text>
			</view>
			<el-upload
				class="upload-demo"
				ref="itinerary"
				action="https://ticket.sxd.cn/api-cms/file/upload"
				:headers="headers"
				:on-success="uploadSuccess"
				:on-exceed="uploadExceed"
				accept=".pdf"
				:limit="1"
			>
				<el-button size="small" type="primary" @click="getUploadIndex(2)">点击上传</el-button>
			</el-upload>
		</view>

		<!-- 上传导游证 -->
		<view class="box__item">
			<view style="margin-bottom: 30rpx">
				<text class="box__item__true">*</text>
				<text class="box__item__title">导游证</text>
			</view>
			<el-upload
				action="https://ticket.sxd.cn/api-cms/file/upload"
				ref="touristCertificate"
				:headers="headers"
				:on-success="uploadSuccess"
				:on-exceed="uploadExceed"
				accept=".png,.jpg"
				:limit="1"
				list-type="picture"
			>
				<el-button size="small" type="primary" @click="getUploadIndex(3)">点击上传</el-button>
			</el-upload>
		</view>

		<uv-modal ref="modal" title="抢票中" align="center" :closeOnClickOverlay="false" @confirm="shouldContinue = false" confirmText="取消抢票">
			<view class="" v-if="!isDelay">
				{{ '正在抢票已刷新' + cont + '次' + '，本次耗时' + randomNumberTime + '毫秒' }}
			</view>
			<view style="display: flex; align-items: center" v-else>
				等待倒计时:
				<lzcCountdown :targetDate="end_time" @countdownFinished="handleCountdownFinished()"></lzcCountdown>
			</view>
		</uv-modal>
		<view style="height: 170px"></view>
		<view class="box__bottom">
			<view style="margin-bottom: 30rpx">
				<text class="box__bottom__title">功能设置</text>
			</view>
			<view class="box__bottom__menu">
				<view class="box__bottom__menu__item">
					<text>随机时间段：</text>
					<uv-switch v-model="isAll" size="40rpx"></uv-switch>
				</view>
				<view class="box__bottom__menu__item">
					<text>提示语音：</text>
					<uv-switch v-model="isAudio" size="40rpx"></uv-switch>
				</view>
			</view>

			<uv-button type="primary" text="开始抢票" @click="submit"></uv-button>
		</view>
	</view>
</template>

<script>
import { getDate, get_time_frame, postCreateOrder } from '@/api/http/robInfo.js';
import { Refresh } from '@/api/http/index.js';
import { format } from 'crypto-js';
import lzcCountdown from '@/components/lzc-countdown/lzc-countdown';
export default {
	data() {
		return {
			headers: {
				Authorization: vk.getVuex('$gl.token.token')
			},
			end_time: '',
			isAll: false, //是否随机时间段
			isAudio: true, //是否开启提示语音
			uploadIndex: 1,
			selected: [], //自定义日历文案
			date: '', //选择的抢票日期
			timeFrameIndex: 0, //选择的抢票时间段的index
			timeIndex: 0, //选择的抢票日期的index
			timeFrameId: 0, //选择的抢票时间段的id
			timePrameList: [], //时段
			timeList: [], //时间段列表
			name: null, //导游姓名
			identificationCard: null, //导游身份证号
			phone: null, //导游电话号码
			visitingListUrl: null, //上传成功的参观名单的url
			itineraryUrl: null, //上传成功的行程单的url
			touristCertificateUrl: null, //上传成功的导游证单的url
			cont: 0,
			shouldContinue: true, //是否循环刷新请求
			randomNumberTime: 1000, //请求时间
			audio: null, //抢票成功的语音
			audioError: null, //抢票失败的语音
			isDelay: false, //是否抢的是延迟一天的时间
			dialogVisible: false, //是否开启查看参观名单的弹窗
			tableData: [], //参观名单列表
			dialogState: 1
		};
	},
	onLoad() {
		this.init();
		this.foundAudio();
		uni.setNavigationBarTitle({
			title: vk.pubfn.isNotNull(vk.getVuex('$gl.token.teamName')) ? vk.getVuex('$gl.token.teamName') : '未绑定公司'
		});
		this.end_time = vk.pubfn.timeFormat(new Date(), 'yyyy-MM-dd') + ' 20:00:01';
	},
	methods: {
		//获取参观名单
		getUserList(state) {
			this.dialogState = state;
			if (state == 1) {
				if (this.$refs.visitingList.uploadFiles.length <= 0) {
					vk.toast('请上传参观名单', 'none');
				} else {
					this.dialogVisible = true;
				}
			} else if (state == 2) {
				if (this.$refs.itinerary.uploadFiles.length <= 0) {
					vk.toast('请上传行程单', 'none');
				} else {
					this.dialogVisible = true;
				}
			}
			this.$forceUpdate();
		},
		//倒计时结束后
		handleCountdownFinished(e) {
			if (this.isDelay) {
				this.isDelay = false;
				this.cont = 0;
				this.shouldContinue = true;
				this.Refresh();
				this.$forceUpdate();
			}
		},
		//初始化提示语音
		foundAudio() {
			this.audio = document.createElement('audio');
			this.audio.src = '../../static/success.mp3';
			this.audioError = document.createElement('audio');
			this.audioError.src = '../../static/error.mp3';
		},
		// 上传超量
		uploadExceed(file, fileList) {
			this.$message({
				showClose: true,
				message: '上传失败！！请删除后再次上传',
				type: 'error'
			});
		},
		// 上传文件
		uploadSuccess(res) {
			if (res.code == 0) {
				this.$message({
					showClose: true,
					message: '上传成功！！',
					type: 'success'
				});
				if (this.uploadIndex == 1) {
					this.visitingListUrl = res.resPath;
					this.tableData = res.data;
				} else if (this.uploadIndex == 2) {
					this.itineraryUrl = res.resPath;
				} else if (this.uploadIndex == 3) {
					this.touristCertificateUrl = res.resPath;
				}
			} else {
				this.$message({
					showClose: true,
					message: res.msg,
					type: 'error',
					duration: 5000
				});
				if (this.uploadIndex == 1) {
					this.$refs.visitingList.clearFiles();
				} else if (this.uploadIndex == 2) {
					this.$refs.itinerary.clearFiles();
				} else if (this.uploadIndex == 3) {
					this.$refs.touristCertificate.clearFiles();
				}
			}
		},
		//获取点击的上传文件按钮的index
		getUploadIndex(state) {
			this.uploadIndex = state;
		},
		//开始抢票
		submit() {
			if (this.date == '') {
				vk.toast('请选择抢票日期', 'none');
			} else if (this.name == null || this.name.trim() == '') {
				vk.toast('请输入导游姓名', 'none');
			} else if (this.identificationCard == null || this.identificationCard.trim() == '') {
				vk.toast('请输入导游身份证号', 'none');
			} else if (this.phone == null || this.phone.trim() == '') {
				vk.toast('请输入导游电话', 'none');
			} else if (this.$refs.visitingList.uploadFiles.length <= 0) {
				vk.toast('请上传参观名单', 'none');
			} else if (this.$refs.itinerary.uploadFiles.length <= 0) {
				vk.toast('请上传行程单', 'none');
			} else if (this.$refs.touristCertificate.uploadFiles.length <= 0) {
				vk.toast('请上传导游证照片', 'none');
			} else {
				if (!this.isDelay) {
					this.cont = 0;
					this.shouldContinue = true;
					this.Refresh();
				}
				this.$refs.modal.open();
			}
		},
		// 初始化页面
		init() {
			getDate({ type: 1 }).then((res) => {
				if (res.code == 0) {
					let startTime = vk.pubfn.getDayOffsetStartAndEnd(1, res.data[res.data.length - 1].day).startTime; //获取三星堆时间段推后一天的时间
					this.timeList = res.data;
					this.timeList.push({
						day: vk.pubfn.timeFormat(startTime, 'yyyy-MM-dd'),
						reception: false,
						stop: true,
						stopEntering: false,
						surplusStock: null,
						timeSlots: null,
						isDelay: true
					});
					this.timeIndex = res.data.findIndex((item) => !item.stopEntering);
					this.date = res.data[this.timeIndex].day;
					this.getTimeFrame(this.date);
				} else {
					this.$message({
						showClose: true,
						message: res.msg,
						type: 'error',
						duration: 5000
					});
				}
			});
		},
		// 获取被点击的时段
		getTimeFrameItem(item, index) {
			this.timeFrameId = item.id;
			this.timeFrameIndex = index;
		},
		// 获取被点击的时间
		getTimeItem(item, index) {
			this.timeIndex = index;
			this.date = item.day;
			if (item.isDelay) {
				this.isDelay = true;
			} else {
				this.isDelay = false;
			}
			this.getTimeFrame(this.date);
		},
		// 获取可抢时段
		getTimeFrame(date) {
			let data = {
				orderType: 1,
				sourceType: 2,
				playDay: date,
				teamType: 1
			};
			get_time_frame(data).then((res) => {
				this.timePrameList = res.data;
				this.timeFrameId = res.data[0].id;
			});
		},

		//提交订单
		postCreateOrder(dataList) {
			let data = dataList;
			postCreateOrder(data).then((res) => {
				if (res.code == 0) {
					this.$refs.modal.close();
					this.$message({
						showClose: true,
						message: '抢票成功',
						type: 'success'
					});
					if (this.isAudio) {
						this.audio.play();
					}
				} else {
					this.$refs.modal.close();
					this.$message({
						showClose: true,
						message: res.msg,
						type: 'error',
						duration: 0
					});
					if (this.isAudio) {
						this.audioError.play();
					}
				}
			});
		},
		//刷新的方法
		Refresh() {
			Refresh({ orderType: 1, sourceType: 2, playDay: this.date, teamType: 1 }).then((res) => {
				if (res.code === 0 && this.shouldContinue) {
					this.cont += 1;
					let foundObject = null; //是否有票
					let timeId = null; // 用于存储找到的时间段的id

					//判断是否开启随机时间段
					if (!this.isAll) {
						timeId = this.timeFrameId;
						foundObject = res.data.some((obj) => {
							if (obj.id === timeId && obj.choose === true) {
								// 执行您的操作
								return true; // 停止迭代
							}
							return false; // 确保返回布尔值
						});
					} else {
						const obj = res.data.find((obj) => obj.choose === true);
						if (obj !== undefined) {
							foundObject = true;
							timeId = obj.id;
						} else {
							foundObject = false;
						}
					}
					//判断是否有票
					if (foundObject) {
						let data = JSON.stringify({
							data: JSON.stringify([
								{
									teamType: 1,
									merchantNo: vk.getVuex('$gl.token.data.merchantNo'),
									isExplanationServiceConsultation: 0,
									contact: this.name,
									contactNumber: this.phone,
									application_file_url: this.itineraryUrl,
									instructions_prove_fileUrl: this.touristCertificateUrl,
									explanationFileUrl: '',
									teamAppointmentItemParamList: [
										{
											planDay: this.date,
											timeSlotId: timeId,
											visitorInformationFileUrl: this.visitingListUrl
										}
									]
								}
							]),
							customerIdCard: this.identificationCard,
							customerIdCardType: 0,
							orderType: 1,
							sourceType: 2,
							payType: 0
						});
						console.log(data);
						let signData = this.zfy.encryptBase64(data);
						let sign = this.zfy.autograph(signData);
						let formData = {
							sign: sign,
							signData: signData
						};
						this.postCreateOrder(formData);
					} else {
						this.randomNumberTime = Math.floor(Math.random() * 301) + 850;
						setTimeout(() => {
							this.Refresh(); // 继续调用Refresh()方法
						}, this.randomNumberTime);
					}
				} else if (!this.shouldContinue) {
					this.$message({
						showClose: true,
						message: '已停止抢票',
						type: 'success'
					});
				} else {
					this.$message({
						showClose: true,
						message: res.msg,
						type: 'error',
						duration: 5000
					});
				}
			});
		}
	},
	computed: {
		listRowStyle() {
			const style = {
				'grid-template-columns': `repeat(${this.timePrameList.length || 2}, 1fr)` // 每行数量
			};

			return style;
		}
	},
	components: { lzcCountdown }
};
</script>

<style lang="scss">
.change {
	color: #fff;
	background-color: #a5864d;
}
.isno {
	background-color: #ddd;
	color: #333;
	border: 2rpx solid #999 !important;
}
view {
	box-sizing: border-box;
}
.box {
	&__item {
		padding: 20rpx;
		display: flex;

		flex-direction: column;
		&__true {
			color: red;
		}

		&__list {
			font-size: 28rpx;
			color: red;
			margin-left: 20rpx;
			text-decoration: underline;
		}
		&__content {
			display: flex;
			align-items: center;
		}
		&__title {
			font-size: 28rpx;
			color: #333;
		}
	}
	&__bottom {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		position: fixed;
		justify-content: space-around;
		bottom: 0;
		width: 100%;
		height: 150px;
		padding: 20rpx;
		left: 0;
		&__menu {
			display: flex;
			align-items: center;
			&__item {
				display: flex;
				align-items: center;
				margin-right: 20rpx;
			}
		}
	}

	&__timePrame,
	&__time {
		width: 100%;
		display: flex;
		flex-direction: column;
		&__box {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 10px;
			padding: 20rpx;
			&__item {
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				padding: 20rpx;
				border-radius: 10rpx;
				border: 2rpx solid #a5864d;
			}
		}
	}
	&__time {
		&__box {
			&__item {
				font-size: 20rpx !important;
				&__txt {
					margin-top: 5rpx;
				}
			}
		}
	}
}
</style>
